/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.kason.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author 卢清波
 * @date 2021/1/27 14:12
 */
public class ChatServer
{

    public static void main(String[] args) throws Exception
    {
        // 定义线程组，主要负责接收客户端请求，通常设置为1个线程
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        // 定义工作线程组，主要负责处理客户端read/write请求，通常设置cpu核心数的2倍
        NioEventLoopGroup worker = new NioEventLoopGroup(8);
        ServerBootstrap server = new ServerBootstrap();
        try
        {
            server.group(boss, worker)
                    // 初始化服务器连接队列大小，服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连
                    .option(ChannelOption.SO_BACKLOG,1024)
                    // 使用NioSctpServerChannel做为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>()
                    {
                        protected void initChannel(SocketChannel ch) throws Exception
                        {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 特殊分隔符分包解码器 分包实现方式有
                            // 1.回车换行 LineBasedFrameDecode ，
                            // 2.特殊字符 DelimiterBasedFrameDecoder，
                            // 3.固定长度 FixedLengthFrameDecoder
                            pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("_".getBytes())));
                            // 加入编解码
                            pipeline.addLast("decoder", new StringDecoder());
                            //向pipeline加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new ChatServerHandler());
                        }
                    });
            System.out.println("服务端启动中。。。。。");
            ChannelFuture channelFuture = server.bind(9000).sync();
            channelFuture.addListener(new ChannelFutureListener()
            {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception
                {
                    if(future.isSuccess())
                    {
                        System.out.println("服务端启动成功");
                    }else{
                        System.out.println("服务端启动失败");
                    }
                }
            });
            channelFuture.channel().closeFuture().sync();
        }
        catch (Exception ex)
        {
            throw ex;
        }finally
        {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }




    }
}
